<template>
  <el-input
    class="common-input"
    ref="input"
    v-model="name"
    :type="type"
    :placeholder="placeholder"
    :maxlength="length"
    :clearable="clearable"
    :prefix-icon="prefixIcon"
    :readonly="readonly"
    :auto-complete="!showPwd ? 'new-password' : 'on'"
    :disabled="disabled"
    :show-word-limit="false"
    :rows="rows"
    @blur="onBlur($event)"
    @focus="$emit('focus', $event)"
    @change="$emit('change', $event)"
    @clear="$emit('clear', $event)"
    @keyup.enter.native="$emit('enter', $event)"
  >
    <slot slot="prefix" name="prefix"></slot>
    <slot slot="suffix" name="suffix"></slot>
    <slot slot="prepend" name="prepend"></slot>
    <slot slot="append" name="append"></slot>
  </el-input>
</template>

<script>
export default {
  name: "CommonInput",
  props: {
    value: {
      type: [String, Number],
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: "text",
    },
    placeholder: {
      type: String,
      default: "",
    },
    maxlength: {
      type: Number,
    },
    showWordLimit: {
      type: Boolean,
      default: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    clearable: {
      type: Boolean,
      default: true,
    },
    rows: {
      type: Number,
      default: 5,
    },
    verify: {
      type: Boolean,
      default: true,
    }, // 是否需要特殊字符校验
    showPwd: {
      type: Boolean,
      default: true,
    }, //浏览器是否显示密码
    prefixIcon: {
      type: String,
    },
  },
  data() {
    return {};
  },
  computed: {
    name: {
      get: function () {
        return typeof this.value === "string"
          ? this.handleSpecialChar(this.value)
          : this.value;
      },
      set: function (v) {
        let value = this.handleSpecialChar(v);
        this.$emit("input", value);
      },
    },
    length: function () {
      return this.maxlength ? this.maxlength : this.type === "text" ? 64 : 256;
    },
  },
  methods: {
    handleSpecialChar(str) {
      if (this.verify) {
        const rule = new RegExp(
          "[^\\u4E00-\\u9FA5\\[\\]A-Za-z0-9*_@.,-:\\s\\n\\(\\（\\)\\）\\,\\，\\.\\。\\;\\；\\！)]"
        );
        str = str.replace(rule, "");
        str = this.handleTrim(str);
      }
      return str;
    },
    handleTrim(v) {
      if (v === " " || v === "" || v === null || v === undefined) {
        return "";
      } else {
        return v.trim();
      }
    },
    onBlur(e) {
      let value = this.handleTrim(this.name);
      // this.$emit('input', value)
      this.$emit("blur", e);
    },
  },
};
</script>

<style scoped lang="scss">
.common-input {
  min-height: 32px !important;

  ::v-deep input {
    min-height: 32px !important;
  }
}
</style>
